package com.ruoyi.equ.service.impl;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.equ.domain.*;
import com.ruoyi.equ.mapper.EquAssetMapper;
import com.ruoyi.equ.service.IEquAssetService;
import com.ruoyi.equ.mapper.EquRepairMapper;
import com.ruoyi.equ.service.IEquRepairService;
import com.ruoyi.equ.service.IEquScrapService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 资产设备Service业务层处理
 *
 * @author ruoyi
 * @date 2025-11-05
 */
@Service
@Slf4j
public class EquAssetServiceImpl implements IEquAssetService
{
    @Autowired
    private EquAssetMapper equAssetMapper;
    @Autowired
    private EquRepairMapper equRepairMapper;

    /**
     * 查询资产设备
     *
     * @param assetId 资产设备主键
     * @return 资产设备
     */
    @Override
    public EquAsset selectEquAssetByAssetId(Long assetId)
    {
        return equAssetMapper.selectEquAssetByAssetId(assetId);
    }

    /**
     * 查询资产设备列表
     *
     * @param equAsset 资产设备
     * @return 资产设备
     */
    @Override
    public List<EquAsset> selectEquAssetList(EquAsset equAsset)
    {
        return equAssetMapper.selectEquAssetList(equAsset);
    }

    /**
     * 查询可以报废的资产设备列表-'正常','待报废'
     *
     * @param equAsset 资产设备
     * @return 资产设备
     */
    @Override
    public List<EquAsset> selectEquAssetListCommon(EquAsset equAsset)
    {
        return equAssetMapper.selectEquAssetListCommon(equAsset);
    }

    /**
     * 新增资产设备
     *
     * @param equAsset 资产设备
     * @return 结果
     */
    @Override
    public int insertEquAsset(EquAsset equAsset)
    {
        equAsset.setCreateTime(DateUtils.getNowDate());
        return equAssetMapper.insertEquAsset(equAsset);
    }

    /**
     * 修改资产设备
     *
     * @param equAsset 资产设备
     * @return 结果
     */
    @Override
    public int updateEquAsset(EquAsset equAsset)
    {
        equAsset.setUpdateTime(DateUtils.getNowDate());
        return equAssetMapper.updateEquAsset(equAsset);
    }

    /**
     * 批量删除资产设备
     *
     * @param assetIds 需要删除的资产设备主键
     * @return 结果
     */
    @Override
    public int deleteEquAssetByAssetIds(Long[] assetIds)
    {
        return equAssetMapper.deleteEquAssetByAssetIds(assetIds);
    }

    /**
     * 删除资产设备信息
     *
     * @param assetId 资产设备主键
     * @return 结果
     */
    @Override
    public int deleteEquAssetByAssetId(Long assetId)
    {
        return equAssetMapper.deleteEquAssetByAssetId(assetId);
    }
    /**
     *
     *获取 距离报废1个月以内的设备信息
     */
    @Override
    public List<EquAsset> selectBroken1MouthEquAssetList(EquAsset equAsset) {
        List<EquAsset> equAssetsList = equAssetMapper.selectEquAssetList(equAsset);
        List<EquAsset> broken1MouthList = new ArrayList<>();
        // 获取当前时间
        Calendar now = Calendar.getInstance();
        // 包含 年月日 时分秒 毫秒 信息

        // 拿到所有信息开始遍历找到 距离报废1个月以内的设备信息
        for (EquAsset equAsset2 : equAssetsList){
            // 获取设备的质保结束日期
            Date warrantyEndTime = equAsset2.getWarrantyEndTime();

            if (warrantyEndTime != null) {
                // 计算距离质保结束还有多少天
                long diffMillis = warrantyEndTime.getTime() - now.getTimeInMillis();
                long diffDays = diffMillis / (24 * 60 * 60 * 1000);

                // 如果距离质保结束日期在0到30天之间，则加入结果列表
                if (diffDays >= 0 && diffDays <= 30) {
                    broken1MouthList.add(equAsset2);
                }
            }
        }
        return broken1MouthList;
    }
    /**
     *
     *获取 距离报废1年以内的设备信息
     */
    @Override
    public List<EquAsset> selectBroken1YearEquAssetList(EquAsset equAsset) {
        List<EquAsset> equAssetsList = equAssetMapper.selectEquAssetList(equAsset);
        List<EquAsset> broken1YearList = new ArrayList<>();
        // 获取当前时间
        Calendar now = Calendar.getInstance();
        // 包含 年月日 时分秒 毫秒 信息

        // 拿到所有信息开始遍历找到 距离报废1年以内的设备信息
        for (EquAsset equAsset2 : equAssetsList) {
            // 获取设备的质保结束日期
            Date warrantyEndTime = equAsset2.getWarrantyEndTime();

            if (warrantyEndTime != null) {
                // 计算距离质保结束还有多少天
                long diffMillis = warrantyEndTime.getTime() - now.getTimeInMillis();
                long diffDays = diffMillis / (24 * 60 * 60 * 1000);

                // 如果距离质保结束日期在0到365天之间，则加入结果列表
                if (diffDays >= 0 && diffDays <= 365) {
                    broken1YearList.add(equAsset2);
                }
            }
        }
        return broken1YearList;
    }
    @Override
    public Map<String, Map<String, Integer>> getEquipmentData() {
        Map<String, Map<String, Integer>> result = new HashMap<>();
        // '全院': { normal: 100, repairing: 20, pendingScrap: 15, scraped: 10 },
        // '眼科': { normal: 30, repairing: 5, pendingScrap: 3, scraped: 2 },
        // '儿科': { normal: 40, repairing: 8, pendingScrap: 5, scraped: 3 }
        // 获取到 所有科室信息
        List<String> useDeptList = equAssetMapper.selectEquAssetDeptList();
        // 初始化所有 正常 待报废 已报废 维修中 的设备数量
//        int normalAll = 0;
//        int repairingAll = 0;
//        int pendingScrapAll = 0;
//        int scrapedAll = 0;
//        // 科室计数器
//        int i = 0;
        // 通过科室信息 查询到各个科室的设备信息
        for (String dept : useDeptList) {
            List<EquAsset> equAssets = equAssetMapper.selectEquAssetListByDept(dept);

            // 初始化状态计数器
            Map<String, Integer> statusCount = new HashMap<>();
            statusCount.put("normal", 0);
            statusCount.put("repairing", 0);
            statusCount.put("pendingScrap", 0);
            statusCount.put("scraped", 0);
            // 初始化各个科室 正常 待报废 已报废 维修中 的设备数量
            int normal = 0;
            int repairing = 0;
            int pendingScrap = 0;
            int scraped = 0;

            // 遍历设备信息
            for (EquAsset equAsset : equAssets) {
                // 获取设备信息 设备状态 '正常','维修中','待报废','已报废'
                String assetStatus = equAsset.getAssetStatus();
                // 通过设备状态 统计不同状态设备的 数量
                if ("正常".equals(assetStatus)) {
                    normal++;
//                    normalAll++;
                } else if ("维修中".equals(assetStatus)) {
                    repairing++;
//                    repairingAll++;
                } else if ("待报废".equals(assetStatus)) {

                    pendingScrap++;
//                    pendingScrapAll++;
                } else if ("已报废".equals(assetStatus)) {
                    scraped++;
//                    scrapedAll++;
                }
            }

            // 更新状态计数
            statusCount.put("normal", normal);
            statusCount.put("repairing", repairing);
            statusCount.put("pendingScrap",pendingScrap);
            statusCount.put("scraped", scraped);
            // 添加到result中
            result.put(dept, statusCount);
            // 当遍历完所有科室设备信息之后 添加 全院设备信息
//            if (i == equAssets.size()){
//                Map<String, Integer> statusAllCount = new HashMap<>();
//                statusAllCount.put("normal", normalAll);
//                statusAllCount.put("repairing", repairingAll);
//                statusAllCount.put("pendingScrap", pendingScrapAll);
//                statusAllCount.put("scraped", scrapedAll);
//                result.put("全院",statusAllCount);
//            }else{
//                // 若未遍历完所有科室设备信息 则 i++ 继续遍历
//                i++;
//            }
        }

        return result;
    }

    @Override
    public List<BrandModelVo> selectAllAssetBrandAndModelSpec() {
        // 最后返回数据初始化
        List<BrandModelVo> brandModelVos = new ArrayList<>();
        // 要返回数据类型
        // private String value;
        //    private String label;
        //    private List<BrandModelChildVo> children;
        // 先拿到所有的品牌
        List<String> brandList = equAssetMapper.selectAllAssetBrand();
        for (String brand : brandList) {
            // 遍历品牌之后通过品牌拿到该品牌所有的型号
            List<String> modelList = equAssetMapper.selectAllAssetModelByBrand(brand);
            // 创建一个存放型号键值的集合
            List<BrandModelChildVo> brandModelChildVos = new ArrayList<>();
            // 创建一个 键值为 全部 null 的集合
            BrandModelChildVo brandAllModelChildVo = new BrandModelChildVo();
            brandAllModelChildVo.setValue(null);
            brandAllModelChildVo.setLabel("全部");
            brandModelChildVos.add(brandAllModelChildVo);
            for (String model : modelList){
                // 遍历型号，设置键值
                BrandModelChildVo brandModelChildVo = new BrandModelChildVo();
                brandModelChildVo.setValue( model);
                brandModelChildVo.setLabel( model);
                brandModelChildVos.add(brandModelChildVo);
            }
            // 添加数据到最终集合中
            BrandModelVo brandModelVo = new BrandModelVo();
            brandModelVo.setValue(brand);
            brandModelVo.setLabel(brand);
            brandModelVo.setChildren(brandModelChildVos);
            brandModelVos.add(brandModelVo);
        }

        System.out.println("这是品牌和型号: " + brandModelVos);
        return brandModelVos;
    }

    @Override
    public List<MonthlyFaultRate> getMonthlyFaultRateData(Map<String, Object> params) {
        // 每个月故障率= 每个月故障的设备数量/设备数量
        List<MonthlyFaultRate> monthlyFaultRates = new ArrayList<>();
        // 先拿到用户提交的品牌名字和型号
        String brand = (String) params.get("brand");
        String model = (String) params.get("model");
//        System.out.println("这是用户提交的品牌和型号: " + brand + " " + model);
        // 通过型号和品牌拿到所有的相对应设备信息
        EquAsset equAsset1 = new EquAsset();
        equAsset1.setAssetBrand(brand);
        equAsset1.setModelSpec(model);
        List<EquAsset> equAssets =equAssetMapper.selectEquAssetList(equAsset1);
        // 遍历设备信息

        for (int i = 1; i < 13; i++) {
        // 查询每一个月的维修信息
            int faultyDeviceCount = 0;//存放每个月维修的工单数量
            for (EquAsset equAsset : equAssets){
                EquRepair equRepair = new EquRepair();
                equRepair.setAssetId(equAsset.getAssetId());
                //获取到指定月份的维修工单数据
                List<EquRepair> equRepairList = equRepairMapper.selectEquRepairListByMonth(equRepair,i);
//                List<EquRepair> equRepairList = equRepairService.selectEquRepairListByMonth(equRepair,i);
                //添加到维修工单数量
                if (equRepairList != null && !equRepairList.isEmpty()) {
                    faultyDeviceCount++;
                }            }
            // 统计好第i个月的故障设备数量之后 计算出该月份的故障率faultRate
            float faultRate = equAssets.size() > 0 ? (float) faultyDeviceCount / equAssets.size() * 100 : 0.0f;
//            System.out.println(i+"月");
//            System.out.println("品牌"+brand+"型号"+model+"设备数量:"+equAssets.size());
//            System.out.println("故障设备数量:"+faultyDeviceCount);
            MonthlyFaultRate monthlyFaultRate = new MonthlyFaultRate();
            monthlyFaultRate.setMonth(i);
            monthlyFaultRate.setFaultRate(faultRate);
            // 添加到结果中
            monthlyFaultRates.add(monthlyFaultRate);
        }
//         遍历最后结果
//        for (MonthlyFaultRate monthlyFaultRate : monthlyFaultRates){
//            System.out.println("这是"+"品牌:"+brand+",型号:"+model+";"+monthlyFaultRate.getMonth()+"月的故障率: " + monthlyFaultRate);
//        }
         return monthlyFaultRates;
    }
    /**
     * 查询所有资产设备名称
     * @return 结果
     * */
    @Override
    public List<String> getAllAssetName() {
        return equAssetMapper.getAllAssetName();
    }


}
